import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Modal, message, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import AuthComponent from '@/components/Authorized/AuthComponent';
import styles from './index.less';
import { pkgTerminalPage, saveTerminal, delTerminal, queryCityInfo } from './service'
import TerminalConfigAddOrEditForm from './components/TerminalConfigAddOrEditForm'

const TerminalConfiguration = () => {

  const actionRef = useRef();
  const ref = useRef()

  // 新增、编辑弹窗显隐
  const [terminalConfigAddOrEditFormVisible, handleTerminalConfigAddOrEditFormVisible] = useState(false)
  // 弹窗名称
  const [modalTitle, handleModalTitle] = useState('')
  // 配置id
  const [configId, handleConfigId] = useState('')
  // 多选
  const [selectedRowKeys, handleSelectedRowKeys] = useState([])

  // 到达航站，出发航站搜索数据
  const { data: selectData = [] } = useRequest(queryCityInfo);
  // 删除接口
  const { run: delTerminalR } = useRequest(params => delTerminal(params), {
    manual: true,
    onSuccess: (data) => {
      message.success('删除成功')
      actionRef.current.reload()
    }
  })

  // 多选改变时方法
  const onSelectChange = selectedRowKeys => {
    handleSelectedRowKeys(selectedRowKeys)
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  };

  // 清空选择性
  const clearSelection = () => {
    handleSelectedRowKeys([])
  };

  // 新增
  const add = () => {
    handleModalTitle('新增航站配置')
    handleConfigId('')
    handleTerminalConfigAddOrEditFormVisible(true)
  }

  // 修改
  const edit = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else if (selectedRows.length > 1) {
      message.warning('只能选择一项')
    } else {
      handleModalTitle('修改航站配置')
      handleConfigId(selectedRows[0].id)
      handleTerminalConfigAddOrEditFormVisible(true)
    }
  }

  // 新增/编辑回调
  const handleTerminalConfig = async fields => {
    try {
      if (configId === '') {
        await saveTerminal(fields)
      } else {
        await saveTerminal({
          id: configId,
          ...fields
        })
      }
      return true
    } catch (error) {
      if (configId === '') {
        message.error('新增失败请重试！');
      } else {
        message.error('修改失败请重试！');
      }
      return false
    }
  }

  // 删除
  const del = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else {
      Modal.confirm({
        title: '删除',
        content: '确认删除该数据？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let ids = []
          selectedRows.map(item => {
            ids.push(item.id)
          })
          delTerminalR({ ids: ids })
        }
      });
    }
  }

  const columns = [
    {
      title: '航站三字码',
      dataIndex: 'airport3code',
      width: 150,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : ''}
          >
            {
              selectData.map(item => (
                <Select.Option key={item.CITY3CODE}>{item.CITYNAME}-{item.CITY3CODE}</Select.Option>
              ))
            }

          </Select>
        );
      },
    },
    {
      title: '航站类型',
      dataIndex: 'airportType',
      width: 120,
      render: (text, _) => (
        <span>
          {text === '1' ? '分公司' : ''}
          {text === '2' ? '本部' : ''}
          {text === '3' ? '运行基地' : ''}
          {text === '4' ? '有代表航站' : ''}
          {text === '5' ? '无代表航站' : ''}
        </span>
      ),
      hideInSearch: true
    },
    {
      title: '航站名称',
      dataIndex: 'airportName',
      width: 120,
      hideInSearch: true
    },
    // {
    //   title: '临时赔偿触发金额',
    //   dataIndex: 'tempCompensationAmount',
    //   width: 160,
    //   hideInSearch: true
    // },
    // {
    //   title: '结案赔偿触发金额',
    //   dataIndex: 'closeCompensationAmount',
    //   width: 160,
    //   hideInSearch: true
    // },
    {
      title: '联系电话1',
      dataIndex: 'phoneFirst',
      width: 180,
      hideInSearch: true
    },
    {
      title: '联系电话2',
      dataIndex: 'phoneSecond',
      width: 120,
      hideInSearch: true
    },
    {
      title: '联系电话3',
      dataIndex: 'phoneThird',
      width: 120,
      hideInSearch: true
    },
    {
      title: '联系邮箱',
      dataIndex: 'emailAddress',
      width: 160,
      hideInSearch: true
    },
    {
      title: '是否统计',
      dataIndex: 'isStatistics',
      width: 120,
      render: (text, _) => (
        <span>{text === 0 ? '不统计' : (text === 1 ? '统计' : '')}</span>
      ),
      hideInSearch: true
    }
  ];
  
  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.terminalConfiguration}
        headerTitle={
          <div>
            <span style={{ fontWeight: "700", color: "rgba(0,0,0,0.85)", fontSize: '16px' }}>航站配置数据列表</span>
          </div>
        }
        options={{ fullScreen: true, reload: false, setting: true, density: false }}
        rowSelection={rowSelection}
        search={{
          span: 6
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode='basicInformation.terminalConfiguration.basic'>
            <Button type="primary" onClick={() => add()} size="small">
              新增
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='basicInformation.terminalConfiguration.edit'>
            <Button type="primary" onClick={() => edit(selectedRows)} size="small">
              修改
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='basicInformation.terminalConfiguration.del'>
            <Button type="primary" onClick={() => del(selectedRows)} size="small">
              删除
            </Button>
          </AuthComponent>
        ]}
        tableAlertRender={false}
        request={params => {
          clearSelection()
          return pkgTerminalPage(params)
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 900, y: 190 }}
      />
      {
        terminalConfigAddOrEditFormVisible && <TerminalConfigAddOrEditForm
          onSubmit={async value => {
            const success = await handleTerminalConfig(value)
            if (success) {
              if (configId === '') {
                message.success('新增成功')
              } else {
                message.success('编辑成功')
              }
              handleTerminalConfigAddOrEditFormVisible(false)
              actionRef.current.reload()
            }
          }}
          onCancel={() => handleTerminalConfigAddOrEditFormVisible(false)}
          terminalConfigAddOrEditFormVisible={terminalConfigAddOrEditFormVisible}
          modalTitle={modalTitle}
          configId={configId}
        ></TerminalConfigAddOrEditForm>
      }
    </>
  );
};

export default Form.create()(TerminalConfiguration);
